using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using WalkingTec.Mvvm.Core;
using UUIDNext;
using HengTong.Model.Db.SupplyChain.Material;
using Microsoft.EntityFrameworkCore;


namespace HengTong.ViewModel.SupplyChain.SysMaterialSkuVms
{
    public partial class SysMaterialSkuVm : CrudVm<SysMaterialSku>
    {
        [Display(Name = "属性列表")]
        public List<string> SelectedAttributesIds { get; set; }
        
        public string MaterialName { get; set; }

        public SysMaterialSkuVm()
        {
            SetInclude(x => x.Unit);
            SetInclude(x => x.Attributes);
        }

        protected override void InitVM()
        {
            SelectedAttributesIds = Entity.Attributes?.Select(x => x.ValueId.ToString()).ToList();
            if (Entity?.MaterialId != null)
            {
                var material = DC.Set<SysMaterial>()
                    .Include(e => e.Attributes)
                    .ThenInclude(e => e.Values)
                    .FirstOrDefault(e => e.ID == Entity.MaterialId);
                Entity.Material = material;
                MaterialName = material?.Name;
            }
        }

        public override async Task DoAddAsync()
        {
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }
            Entity.Attributes = new List<SysMaterialSkuAttributes>();
            if (SelectedAttributesIds != null)
            {
                foreach (var id in SelectedAttributesIds)
                {
                     SysMaterialSkuAttributes middle = new SysMaterialSkuAttributes();
                    middle.SetPropertyValue("ValueId", id);
                    Entity.Attributes.Add(middle);
                }
            }

            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }
            Entity.Attributes = new List<SysMaterialSkuAttributes>();
            if(SelectedAttributesIds != null )
            {
                 foreach (var item in SelectedAttributesIds)
                {
                    SysMaterialSkuAttributes middle = new SysMaterialSkuAttributes();
                    middle.SetPropertyValue("ValueId", item);
                    Entity.Attributes.Add(middle);
                }
            }

            await base.DoEditAsync(updateAllFields);
        }

    }
}
